package com.ling.controller;

import com.ling.bean.AnswerComment;
import com.ling.bean.Msg;
import com.ling.bean.UserMessage;
import com.ling.service.AnswerCommentService;
import com.ling.service.UserMessageService;
import com.ling.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Controller
public class AnswerCommentController {
    private final AnswerCommentService answerCommentService;
    private final UserMessageService userMessageService;
    @Autowired
    public AnswerCommentController(AnswerCommentService answerCommentService, UserMessageService userMessageService) {
        this.answerCommentService = answerCommentService;
        this.userMessageService = userMessageService;
    }

    //获取指定回答的评论数据
    @GetMapping(value = "/answer/comment/{answerId}")
    @ResponseBody
    public Msg getAnswerComments(@PathVariable String answerId) {
        List<AnswerComment> answerCommentByAnswerId = answerCommentService.getAnswerCommentByAnswerId(answerId);
        return Msg.success().add("comments",answerCommentByAnswerId);
    }

    //提交评论
    @PostMapping(value = "/submit/answer/comment")
    @ResponseBody
    public Msg submitAnswerComment(@RequestParam String answerid, @RequestParam String fromuserid, @RequestParam String fromusername, @RequestParam String touserid, @RequestParam String tousername, @RequestParam String message) {
        AnswerComment answerComment = new AnswerComment();
        answerComment.setId(StringUtil.getRandomString(16));
        answerComment.setAnswerid(answerid);
        answerComment.setComment(message);
        answerComment.setEdittime(new Date());
        answerComment.setFromuserid(fromuserid);
        answerComment.setFromusername(fromusername);
        answerComment.setTouserid(touserid);
        answerComment.setTousername(tousername);
        answerCommentService.addAnswerComment(answerComment);

        //用户收到消息
        UserMessage userMessage = new UserMessage();
        userMessage.setEdittime(new Date());
        userMessage.setFromuserid(fromuserid);
        userMessage.setFromusername(fromusername);
        userMessage.setHasread(0);
        userMessage.setId(StringUtil.getRandomString(16));
        userMessage.setMessagecontent("在评论区提到了你。");
        userMessage.setMessagetype(4);
        userMessage.setMessagetypeid(answerid);
        userMessage.setUserid(touserid);
        userMessageService.saveUserMessage(userMessage);
        return Msg.success();
    }
}
